import javax.swing.*;
import java.awt.*;
import java.util.Random;
// Press Shift twice to open the Search Everywhere dialog and type `show whitespaces`,
// then press Enter. You can now see whitespace characters in your code.
public class Game2048 extends JPanel {
    private static final int SIZE = 4;
    private final int[][] grid = new int[SIZE][SIZE];
    private final Random random = new Random();

    Game2048() {
        spawnTile();
        spawnTile();
    }

    private void spawnTile() {
        int x,y;
        do {
            x = random.nextInt(SIZE);
            y = random.nextInt(SIZE);
        }while (grid[x][y] != 0);

        grid[x][y] = random.nextInt(10) < 5 ? 2 : 4;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.LIGHT_GRAY);
        g.fillRect(0,0,getWidth(),getHeight());
        for(int i=0;i<SIZE;i++) {
            for(int j=0;j<SIZE;j++) {
                //画小格子
                drawTile(g,grid[i][j],j*100,i*100);
            }
        }
    }
    //g画笔，value:格子上的数字，x,y为格子上的坐标
    private void drawTile(Graphics g, int value, int x, int y) {
        int r = (int) (Math.log(value)/Math.log(2));
        g.setColor(value == 0 ? Color.GRAY : new Color(255-r*20,240,200));
        g.fillRect(x,y,100,100);
        g.setColor(Color.BLACK);
        g.drawRect(x,y,100,100);

        if(value != 0) {
            String  text = String.valueOf(value);
            FontMetrics fm = g.getFontMetrics();
            int w = fm.stringWidth(text);
            int h = fm.getHeight();
            int textX = x + (100-w)/2;
            int textY = y + (100-h)/2 + fm.getAscent();
            g.drawString(text,textX,textY);
        }
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("2048 Game");
        frame.setSize(420,460);
        Game2048 game2048 = new Game2048();
        frame.add(game2048);
        frame.setVisible(true);

    }
}